package org.example;

import com.zaxxer.hikari.HikariDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class UtilTool {
    private static final Logger logger = Logger.getLogger(UtilTool.class.getName());
    private static final int MAX_RETRY = 5;
    private static final Scanner scanner = new Scanner(System.in);
    private static HikariDataSource dataSource;

    public static Connection getConnection() throws SQLException {
        Connection conn = dataSource.getConnection();
        try (Statement stmt = conn.createStatement()) {
            ResultSet rs = stmt.executeQuery("SELECT VERSION()");
            if (rs.next()) {
                logger.info("成功连接到数据库，版本：" + rs.getString(1));
            }
        }
        return conn;
    }


    public static int getNumberInput(String prompt, int min, int max) throws Main.MenuExitException {
        int retry = 0;
        while (retry < MAX_RETRY) {
            try {
                System.out.print(prompt);
                String input = scanner.nextLine().trim();
                int num = Integer.parseInt(input);

                if (num >= min && num <= max) {
                    return num;
                }

                System.out.printf("[错误] 输入范围应为 %d-%d（剩余尝试次数：%d）\n",
                        min, max, MAX_RETRY - retry - 1);
                retry++;
            } catch (NumberFormatException e) {
                System.out.printf("[错误] 无效的数字格式（剩余尝试次数：%d）\n", MAX_RETRY - retry - 1);
                retry++;
            }
        }
        throw new Main.MenuExitException("超过最大重试次数");
    }


    public static String getPhoneNumber() throws Main.MenuExitException {
        for (int retry = 0; retry < MAX_RETRY; retry++) {
            System.out.print("请输入电话号码：");
            String num = scanner.nextLine().trim();
            if (num.matches("\\d{7,15}")) {
                return num;
            }
            System.out.printf("[错误] 无效号码格式（剩余尝试次数：%d）\n", MAX_RETRY - retry - 1);
        }
        throw new Main.MenuExitException("超过最大重试次数");
    }


    public static LocalDate getDate(String prompt) throws Main.MenuExitException {
        for (int retry = 0; retry < MAX_RETRY; retry++) {
            System.out.print(prompt);
            try {
                return LocalDate.parse(scanner.nextLine(), DateTimeFormatter.ISO_DATE);
            } catch (Exception e) {
                System.out.printf("[错误] 日期格式无效（剩余尝试次数：%d）\n", MAX_RETRY - retry - 1);
            }
        }
        throw new Main.MenuExitException("超过最大重试次数");
    }

    public static LocalDate[] getDateRange() throws Main.MenuExitException {
        while (true) {
            LocalDate start = getDate("起始日期（YYYY-MM-DD）：");
            LocalDate end = getDate("结束日期（YYYY-MM-DD）：");

            if (!end.isBefore(start)) {
                return new LocalDate[]{start, end};
            }
            System.out.println("[错误] 结束日期不能早于开始日期");
        }
    }
}
